package com.runmi.webchat.aftersale.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.runmi.webchat.aftersale.common.utils.HttpUtil;
import com.runmi.webchat.aftersale.web.api.vo.UserAccessTockenVo;
import com.runmi.webchat.aftersale.web.api.vo.UserInfoVo;

@Component
public class WxUtil {
	
	
	
	  private WxServiceConfig wxConfig=new WxServiceConfig();
	  
	  protected static final Log log = LogFactory.getLog("logFile");

	 /**
     * 获取微信获取用户信息重定向URL
     * @param redirectUrl
     * @param state 需要返回的参数
     * @return
     */
    public String getRequestCodeUrl(String redirectUrl,String state) {
        return String.format(Constants.WX_OPENAPI_URL + "/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect",
                wxConfig.getAppid(), redirectUrl, "snsapi_userinfo", state);
    }

    /**
     * 获取用户OPENiD
     * @return
     */
    public UserAccessTockenVo getUserOpenId(String code){
        //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        String result="";
        String url=String.format("%s/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",Constants.WX_API_URL,wxConfig.getAppid(),wxConfig.getSecret(),code);
        log.info("getUserOpenId code:"+code + " url:" +url);
        String json= HttpUtil.doGetSSL(url,null);
        log.info("getUserOpenId: code"+code + " return:" + json);
        UserAccessTockenVo userAccessTockenVo= JSON.parseObject(json, new TypeReference<UserAccessTockenVo>(){});
        return userAccessTockenVo;
        //        if(null!=userAccessTockenVo){
//            return userAccessTockenVo.getOpenid();
//        }else{
//            return "";
//        }
    }

    public UserInfoVo getUserInfo(String tocken,String openId){
        //String result="";
        String url=String.format("%s/sns/userinfo?access_token=%s&openid=%s&&lang=zh_CN",Constants.WX_API_URL,tocken,openId);
        log.info("getUserOpenId code:"+tocken + " url:" +url);
        String json= HttpUtil.doGetSSL(url,null);
        log.info("getUserOpenId: code"+tocken + " return:" + json);
        UserInfoVo userInfo= JSON.parseObject(json, new TypeReference<UserInfoVo>(){});
        return userInfo;
    }
}
